<template>
  <div class="zhzx-left-top d-flex-c">
    <div class="panel-header-bg flex-between">
      <div class="title-text">
        雨情信息
      </div>
      <SwitchTab
        :tab-list="queryTabList"
        v-model="yqQueryType"
        @change="getRainInfo"
      />
    </div>
    <div class="d-flex-c panel-zone-big-bg left-top flex-1">
      <div
        class="panel-zone-bg  m-b-mini rain-desc-box flex-1"
      >
        <div class="little-title m-b-mini">
          雨情概述
        </div>
        <div
          class="p-l-mini f-14"
          v-html="htmlRainDesc"
        />
      </div>

      <div
        class="flex-between m-b-mini flex-0"
        style="height: 230px;"
      >
        <div
          class="panel-zone-bg m-r-mini flex-1 full-height"
        >
          <div class="little-title flex-0">
            实况降雨
          </div>
          <div class="flex-1">
            <BKChart
              :option="actualRainfallOptions"
            />
          </div>
        </div>
        <div
          class="panel-zone-bg flex-0  full-height"
          style="width: 240px;"
        >
          <div
            class="little-title m-b-tiny"
          >
            降雨等级统计
          </div>
          <div class="rain-level-box flex-wrap">
            <div
              v-for="(item,index) in rainLevelList"
              :key="index"
              class="rain-level-item d-flex-c jc-c ai-c"
            >
              <div
                :class="item.type"
                class="ff-agencyyr c-text-blue rain-level-value c-pointer"
                @click="showReverseCheck(item)"
              >
                {{ item.value }}
              </div>
              <div class="f-14 c-white">
                {{ item.label }}
              </div>
              <div class="c-text-gray f-12">
                {{ item.desc }}
              </div>
            </div>
          </div>
        </div>
      </div>

      <div
        class="panel-zone-bg rain-alarm-box flex-1"
      >
        <div class="flex-between ai-c">
          <div class="little-title">
            降雨告警
          </div>
          <SwitchTab
            :tab-list="queryHourList"
            v-model="rainQueryType"
            @change="setRainAlarmOptions()"
          />
        </div>
        <div
          v-loading="loading"
          class="flex-1 overflow-hidden position-relative"
        >
          <BKChart
            :option="rainAlarmOptions"
          />
        </div>
      </div>
    </div>
    <DetailModal
      v-if="detailVisible"
      :visible="detailVisible"
      :columns="detailColumns"
      :static-data="detailData"
      @close="detailVisible=false"
      width="1236px"
    />
  </div>
</template>

<script>
import DetailModal from '@/views/business/ysqjcdp/components/modal/detail-modal.vue'
import SwitchTab from '@/views/business/ysqjcdp/components/switch-tab.vue'
import { getBarOption, verticalXAXisLabel } from '@/components/chart/echart-utils'
export default {
  name: 'ZhzxLeftTop',
  components: { SwitchTab, DetailModal },
  data () {
    this.queryHourList = [
      {
        label: '今日以来',
        value: '100',
        code: '1'
      },
      {
        label: '近1h',
        value: '30',
        code: '3'
      }, {
        label: '近3h',
        value: '60',
        code: '4'
      },
      {
        label: '近6h',
        value: '80',
        code: '5'
      }
    ]
    this.rainAlarmLegends = [
      {
        name: '超30mm',
        iconType: 'rect',
        color: '#07FFDE',
        field: 'over30',
        unit: '个'
      },
      {
        name: '超60mm',
        iconType: 'rect',
        color: '#0382fc',
        field: 'over60',
        unit: '个'
      },
      {
        name: '超100mm',
        iconType: 'rect',
        field: 'over100',
        color: '#FFB948',
        unit: '个'
      }
    ]
    return {
      yqQueryType: '1',
      loading: false,
      isFirst: true,
      rainQueryType: '100',
      LEADER: this.$store.state.user.userInfo.dept.LEADER,
      rainLevelList: [
        { label: '小雨', value: 0, desc: '1-10mm', range: [1, 10] },
        { label: '中雨', value: 0, desc: '10-25mm', range: [10, 25] },
        { label: '大雨', value: 0, desc: '25-50mm', range: [25, 50] },
        { label: '暴雨', value: 0, desc: '50-100mm', range: [50, 100] },
        { label: '大暴雨', value: 0, desc: '100-250mm', type: 'yellow', range: [100, 250] },
        { label: '特大暴雨', value: 0, desc: '250mm以上', type: 'red', range: [250] }
      ],
      actualRainfallOptions: null,
      rainAlarmOptions: null,
      rainLevelData: [],
      htmlRainDesc: '',
      detailVisible: false,
      detailColumns: [
        { title: '站码', field: 'stcd', width: 100 },
        { title: '测站名称', field: 'stnm', minWidth: 100 },
        { title: '雨量值', field: 'rainValue', width: 100 },
        { title: '站址', field: 'stlc', minWidth: 120 },
        { title: '站类', field: 'sttp', width: 80 },
        { title: '所属行政区名', field: 'addvnm', width: 120 },
        { title: '经度', field: 'lgtd', width: 120 },
        { title: '纬度', field: 'lttd', width: 120 }
      ],
      detailData: []
    }
  },
  computed: {
    queryTabList () {
      return [
        {
          label: '今日以来',
          value: '1'
        },
        {
          label: new Date().getHours() + '时以来',
          value: '2'
        },
        {
          label: '1h',
          value: '3'
        },
        {
          label: '3h',
          value: '4'
        },
        {
          label: '6h',
          value: '5'
        },
        {
          label: '12h',
          value: '6'
        }, {
          label: '24h',
          value: '7'
        }
      ]
    }
  },
  mounted () {
    this.getRainInfo()
  },
  methods: {
    // 获取所有接口信息
    getRainInfo () {
      this.getRainLevel()
      this.setActualRainfallOptions()
      this.getYQGSData()
    },
    // 雨情概述
    async getYQGSData () {
      const data = await this.$request.formDataPost(window.outApiHw1 + 'hw-api/outInterface/selectOverviewRainSituation', { })
      let qs = '0'
      if (data.areaList) {
        const hb = data.areaList.find(c => c.name === '河北省')
        if (hb) {
          qs = this.getNum(hb.rainValue)
        }
      }
      let str = `全省面雨量${qs}mm`
      if (data.basin) {
        let basin = data.basin.sort((a, b) => {
          return Number(b.rainValue) - Number(a.rainValue)
        })
        str = str + '，其中'
        basin = basin.slice(0, 3)
        for (let i = 0; i < basin.length; i++) {
          str = str + `${basin[i].name}${this.getNum(basin[i].rainValue)}mm`
          if (i === basin.length - 1) {
            str = str + '。'
          } else {
            str = str + '，'
          }
        }
      }
      if (data.areaList) {
        let areaList = data.areaList.filter(c => c.name !== '河北省').sort((a, b) => {
          return Number(b.rainValue) - Number(a.rainValue)
        })
        str = str + '行政分区前三位为'
        areaList = areaList.slice(0, 3)
        for (let i = 0; i < areaList.length; i++) {
          str = str + `${areaList[i].name}${this.getNum(areaList[i].rainValue)}mm`
          if (i === areaList.length - 1) {
            str = str + '。'
          } else {
            str = str + '，'
          }
        }
      }
      this.htmlRainDesc = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + str.replace(/(\d+(\.\d+)?mm)/g, (match) => {
        return '<span class=\'c-text-blue\'>' + match + '</span>'
      })
    },
    // 实况降雨
    async setActualRainfallOptions () {
      const data = await this.$request.formDataPost(window.outApiHw + 'hw-api/outInterface/selectActualPrecipitation',
        { type: this.yqQueryType, areaCode: this.LEADER }
      )
      const result = getBarOption({
        yAxisName: 'mm',
        xAxis: data.map(r => r.name),
        series: [
          {
            name: '降雨量',
            type: 'bar',
            color: ['#0382FC00', '#0382fc'],
            data: data.map(r => {
              return {
                ...r,
                value: r.rainValue
              }
            })
          }
        ]
      })
      if (!data.length) {
        result.grid.left = 20
      }
      result.grid.bottom = -6
      result.series[0].itemStyle.borderRadius = [12, 12, 0, 0]
      // result.series[0].label = {
      //   show: true,
      //   position: 'top',
      //   fontSize: '14px',
      //   color: '#fff'
      // }
      result.series[0].barMaxWidth = 12
      result.xAxis.axisLabel.color = '#FFFFFF'
      result.yAxis.axisLabel.color = '#FFFFFF'
      result.xAxis.axisLine = {
        show: true,
        lineStyle: {
          color: 'rgba(233,237,240,0.1)'
        }
      }
      result.xAxis.axisLabel.interval = 0
      result.xAxis.axisLabel.formatter = verticalXAXisLabel
      result.yAxis.splitLine.show = false
      result.yAxis.axisLine = {
        show: true,
        lineStyle: {
          color: 'rgba(233,237,240,0.1)'
        }
      }
      result.yAxis.nameTextStyle = {
        color: '#C4CBD9',
        fontSize: '14px',
        padding: [0, 0, 0, -20]
      }
      result.tooltip.appendToBody = true
      this.actualRainfallOptions = result
    },
    // 降雨等级统计
    async getRainLevel () {
      const data = await this.$request.formDataPost(window.outApiHw + 'hw-api/outInterface/selectProductRains',
        { type: this.yqQueryType, areaCode: this.LEADER }
      )
      this.rainLevelData = data
      const key = this.getEndZero(this.LEADER) > 2 ? 'city' : 'county'
      this.rainLevelList.forEach((o) => {
        const keys = []
        data.map((p) => {
          if ((o.range.length > 1 && o.range[0] <= p.rainValue && p.rainValue < o.range[1]) || (o.range.length === 1 && o.range[0] <= p.rainValue)) {
            !keys.includes(p[key]) && keys.push(p[key])
          }
        })
        o.value = keys.length
      })
      this.isFirst && this.setRainAlarmOptions()
    },
    // 降雨告警
    async setRainAlarmOptions (isFirst = this.isFirst) {
      let data_ = []
      if (!isFirst) {
        this.loading = true
        const type = this.queryHourList.find((o) => o.value === this.rainQueryType).code
        data_ = await this.$request.formDataPost(window.outApiHw + 'hw-api/outInterface/selectProductRains',
          { type, areaCode: this.LEADER }
        )
      }
      this.loading = false
      const data = isFirst ? this.rainLevelData : data_
      this.isFirst && (this.isFirst = false)
      const key_ = this.getEndZero(this.LEADER) > 2 ? 'city' : 'county'
      const citys = []
      data.forEach((o) => {
        if (!o[key_]) return
        if (citys.every((item) => item.label !== o[key_])) {
          citys.push({
            label: o[key_],
            data: [],
            value: 0
          })
        }
      })
      citys.forEach((o) => {
        data.forEach((p) => {
          if (o.label === p[key_]) {
            if (Number(p.rainValue) > Number(this.rainQueryType)) {
              o.value += 1
            }
            o.data.push(p)
          }
        })
      })
      const result = getBarOption({
        yAxisName: '(个)',
        xAxis: citys.map(r => r.label),
        series: [
          {
            type: 'bar',
            name: '站点个数',
            color: ['#07FFDE00', '#07FFDE'],
            xAxisIndex: 1,
            zlevel: 8,
            data: citys.map(r => {
              return {
                ...r,
                value: r.value
              }
            })
          }
        ]
      })
      if (!citys.length) {
        result.grid.left = 20
      }
      result.grid.right = 0
      result.grid.top = 5
      result.series.forEach(serie => {
        serie.itemStyle.borderRadius = [12, 12, 0, 0]
        serie.barMaxWidth = 12
      })
      result.yAxis.axisLabel.color = '#FFFFFF'
      result.xAxis = [{
        ...result.xAxis,
        axisLabel: {
          show: true,
          interval: 0,
          color: '#FFFFFF'
        },
        axisLine: {
          show: true,
          lineStyle: {
            color: 'rgba(233,237,240,0.1)'
          }
        }
      }, {
        ...result.xAxis,
        show: false
      },
      {
        ...result.xAxis,
        show: false
      }
      ]
      result.yAxis.splitLine.show = false
      result.yAxis.axisLine = {
        show: true,
        lineStyle: {
          color: 'rgba(233,237,240,0.1)'
        }
      }
      result.yAxis.nameTextStyle = {
        color: '#FFFFFF',
        fontSize: '12px',
        padding: [0, 0, 0, -20]
      }
      result.tooltip.appendToBody = true
      result.tooltip.formatter = params => {
        let result = params[0].name + '<br>'
        params.forEach(function (item) {
          result += item.marker + ' ' + item.seriesName + `<span style='font-weight:700;margin-left:12px;'>${item.value}</span>` + ' <br>' // 对柱状图数据进行格式化
        })
        return result
      }
      if (citys.length > 10) {
        result.dataZoom = [{
          type: 'slider',
          width: '80%',
          start: 0,
          end: 50,
          left: '11%',
          right: '9%',
          showDataShadow: false,
          brushSelect: false,
          height: '10px',
          handleSize: '20%',
          borderColor: '#1376D3',
          backgroundColor: '#154cc2cc',
          bottom: '2px',
          handleStyle: {
            borderWidth: 0,
            color: '#346194'
          },
          textStyle: {
            color: '#fff'
          }
        }, {
          type: 'inside'
        }]
      } else {
        result.grid.bottom = 4
      }

      this.rainAlarmOptions = result
    },
    // 判断字符串结尾多少个0
    getEndZero (str) {
      let count = 0
      for (let i = str.length - 1; i >= 0; i--) {
        if (str[i] === '0') {
          count++
        } else {
          break
        }
      }
      return count
    },
    getNum (val) {
      if (val === null || val === undefined || isNaN(Number(val)) || val === '') {
        return '0'
      }
      return val
    },
    showReverseCheck (o) {
      this.detailVisible = true
      const keys = []
      const result = []
      const key = this.getEndZero(this.LEADER) > 2 ? 'city' : 'county'
      this.rainLevelData.map((p) => {
        if ((o.range.length > 1 && o.range[0] <= p.rainValue && p.rainValue < o.range[1]) || (o.range.length === 1 && o.range[0] <= p.rainValue)) {
          !keys.includes(p[key]) && keys.push(p[key]) && result.push(p)
        }
      })
      this.detailData = result
      // console.log({ o, keys, result }, this.rainLevelData)
    }
  }
}
</script>

<style lang="scss" scoped>
.rain-desc-box {
  min-height: 90px;
  max-height: 100px;
  position: relative;

  &::after {
    content: "";
    position: absolute;
    bottom: 0;
    right: 0;
    background-image: url("~@/assets/images/ysqjcdp/rain-desc.png");
    background-size: 100% 100%;
    width: 581px;
    height: 28px;
  }
}

.rain-level-box {
  gap: 5px 7px;

  .rain-level-item {
    background: url("~@/assets/images/ysqjcdp/rain-level.png") no-repeat left top;
    background-size: 100% 100%;
    width: calc((100% - 10px) / 2);
    height: 60px;

    span {
      text-align: center;
      line-height: 12px;
    }

    .rain-level-value {
      line-height: 20px;
      font-size: 20px;
      font-weight: 700;
      text-align: center;

      &.yellow {
        color: #ff8d2c;
      }

      &.red {
        color: #e03636;
      }
    }
  }
}

.rain-alarm-box {
  min-height: 120px;
  // max-height: 220px;
}

.chart-legend-position {
  position: absolute;
  right: 34px;
  top: 8px;
}

</style>
